<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>vue2.0一起在懵逼的海洋里越陷越深（六） | leenty blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="前言本文章系列：vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)演示场地vue2.0 Demo,这是源码地址,觉得靠谱的话欢迎加星跟随,有问题欢迎评论和指正😃 在vue开发SPA应用的过程中，多数情况下我们需要解决一个问题就是在路由跳转的过程中需要更新你SPA应用的title ，这一节不说其他，就展示如何使用vue-router的导航钩子去解">
<meta name="keywords" content="vuejs,vue-router">
<meta property="og:type" content="article">
<meta property="og:title" content="vue2.0一起在懵逼的海洋里越陷越深（六）">
<meta property="og:url" content="http://baidu.com/2016/12/18/vue2-6/index.html">
<meta property="og:site_name" content="leenty blog">
<meta property="og:description" content="前言本文章系列：vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)演示场地vue2.0 Demo,这是源码地址,觉得靠谱的话欢迎加星跟随,有问题欢迎评论和指正😃 在vue开发SPA应用的过程中，多数情况下我们需要解决一个问题就是在路由跳转的过程中需要更新你SPA应用的title ，这一节不说其他，就展示如何使用vue-router的导航钩子去解">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.leenty.com/img/vue/huaji_ld.jpg">
<meta property="og:image" content="http://www.leenty.com/img/vue/mdzz.jpg">
<meta property="og:updated_time" content="2016-12-20T02:05:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue2.0一起在懵逼的海洋里越陷越深（六）">
<meta name="twitter:description" content="前言本文章系列：vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)演示场地vue2.0 Demo,这是源码地址,觉得靠谱的话欢迎加星跟随,有问题欢迎评论和指正😃 在vue开发SPA应用的过程中，多数情况下我们需要解决一个问题就是在路由跳转的过程中需要更新你SPA应用的title ，这一节不说其他，就展示如何使用vue-router的导航钩子去解">
<meta name="twitter:image" content="http://www.leenty.com/img/vue/huaji_ld.jpg">
  
    <link rel="alternative" href="/atom.xml" title="leenty blog" type="application/atom+xml">
  
  
    <link rel="icon" href="//favicon.png">
  
  <script src="/style.js"></script>
  

  
<!-- baidu_tongji -->
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?5bae4c35e53fde3bf2526312c3edaf1d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
<!-- End baidu_tongji -->


</head>
</html>
<body>
  <div id="container">
    <div class="left-col">
      <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img src="/img/default_avatar.png" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">leenty</a></h1>
		</hgroup>

		

		<nav class="header-menu">
			<ul>
			
				<li><a href="/">主页</a></li>
	        
				<li><a href="/archives">所有文章</a></li>
	        
			</ul>
		</nav>
		<nav class="header-smart-menu">
	        
    		
    			
    			<a class="js-smart-menu" data-idx="0" href="javascript:void(0)">所有文章</a>
    			
    			
            
    			
    			<a class="js-smart-menu" data-idx="1" href="javascript:void(0)">标签</a>
    			
    			
            
    			
    			<a class="js-smart-menu" data-idx="2" href="javascript:void(0)">友链</a>
    			
    			
            
    			
    			<a class="js-smart-menu" data-idx="3" href="javascript:void(0)">关于我</a>
    			
    			
            
		</nav>
		<nav class="header-nav">
			<div class="social">
				
					<a class="github" target="_blank" href="https://github.com/leenty" title="github">github</a>
		        
			</div>
		</nav>
	</header>		
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"><i class="icon-list"></i></div>
  		<h1 class="header-author js-mobile-header hide">leenty</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				
					<img src="/img/default_avatar.png" class="js-avatar">
				
			</div>
			<hgroup>
			  <h1 class="header-author">leenty</h1>
			</hgroup>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/archives">所有文章</a></li>
		        
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="https://github.com/leenty" title="github">github</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap">
        <article id="post-vue2-6" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      vue2.0一起在懵逼的海洋里越陷越深（六）
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>本文章系列：<a href="http://leenty.com/tags/vuejs/" target="_blank" rel="noopener">vue2.0一起在懵逼的海洋里越陷越深 (http://leenty.com/tags/vuejs/)</a><br><a href="http://vue2.leenty.com" target="_blank" rel="noopener">演示场地vue2.0 Demo</a>,这是<a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">源码地址</a>,觉得靠谱的话欢迎加星跟随,有问题欢迎评论和指正😃</p>
<p>在vue开发SPA应用的过程中，多数情况下我们需要解决一个问题<br>就是在路由跳转的过程中需要更新你SPA应用的<code>title</code> ，<br>这一节不说其他，就展示如何使用<code>vue-router</code>的<strong>导航钩子</strong>去解决这么一个问题。<br>接下来就愉快的去玩耍啦！<br><img src="http://www.leenty.com/img/vue/huaji_ld.jpg" alt="红红火火恍恍惚惚"></p>
<h3 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h3><p>好的，介绍下背景，我有这么一个<a href="http://vue2.leenty.com" target="_blank" rel="noopener">博客的demo</a>，里面有多个版块，每个版块有着不同的名称(<code>title</code>)<br>先看一下Demo的路由结构<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">vue2.leenty.com</span><br><span class="line">├── home                # 首页版块</span><br><span class="line">├── article             # 文章版块</span><br><span class="line">│   ├── vue2-1            # 具体文章一</span><br><span class="line">│   ├── vue2-2            # 具体文章二</span><br><span class="line">│   ├── vue2-3            # 具体文章三</span><br><span class="line">│   ├── vue2-4            # 具体文章四</span><br><span class="line">│   ├── vue2-5            # 具体文章五</span><br><span class="line">│   └── vue2-6            # 具体文章六</span><br><span class="line">└── demo                # 演示版块</span><br><span class="line">    └── demo-1            # 具体演示一</span><br></pre></td></tr></table></figure></p>
<p>好的，接下来要实现的是在切换路由的时候同时的去切换你页面的<code>title</code></p>
<h4 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h4><p>这里思路是使用<code>vue-router</code>的路由全局导航钩子去解决这个问题<br>在路由对象里添加一个<code>title</code>字段以供路由全局导航钩子读取并更新页面<code>title</code></p>
<h4 id="配置路由"><a href="#配置路由" class="headerlink" title="配置路由"></a>配置路由</h4><p>所以第一步，先在路由对象里添加这一个字段。<br>打开<code>src/routes.js</code>(<a href="https://github.com/leenty/vue2/blob/master/src/routes.js" target="_blank" rel="noopener">源文件地址：https://github.com/leenty/vue2/blob/master/src/routes.js</a>)<br><strong>（注意是<code>routes.js</code>,这是咱用来存放路由对象的文件）</strong><br>在原有数据的基础上添加<code>title</code><br>这里其实vue1.0和vue2.0的实现是差不多的，所以vue1.0也是可以使用的。<br>vue2.0路由对象提供了一个<code>meta</code>字段来给你存放一些其他信息，所以这里就可以用来存放<code>title</code><br>vue1.0的话是没有这个字段的，所以可以直接与<code>path</code>平级。<br>具体如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> routes = [</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Home'</span>,</span><br><span class="line">    path: <span class="string">'/'</span>,</span><br><span class="line">    meta: &#123;</span><br><span class="line">      title: <span class="string">'home'</span> <span class="comment">// 主页的title为home</span></span><br><span class="line">    &#125;,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Home.vue'</span>)</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Article'</span>,</span><br><span class="line">    path: <span class="string">'/article'</span>,</span><br><span class="line">    meta: &#123;</span><br><span class="line">      title: <span class="string">'article'</span> <span class="comment">// 文章模块相应的title为article</span></span><br><span class="line">    &#125;,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Article.vue'</span>),</span><br><span class="line">    children: [</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'vue2_1'</span>,</span><br><span class="line">        path: <span class="string">'/article/vue2_1'</span>,</span><br><span class="line">        meta: &#123;</span><br><span class="line">          title: <span class="string">'vue2.0一起在懵逼的海洋里越陷越深（一）'</span> <span class="comment">// 子路由也是一样的道理</span></span><br><span class="line">        &#125;,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./md/articles/vue2-1.md'</span>)</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="comment">// ... 子路由和父路由都差不多，所以后面的就省略了</span></span><br><span class="line">    ]</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'Demo'</span>,</span><br><span class="line">    path: <span class="string">'/demo'</span>,</span><br><span class="line">    meta: &#123;</span><br><span class="line">      title: <span class="string">'demo'</span> <span class="comment">// 演示模块title为demo</span></span><br><span class="line">    &#125;,</span><br><span class="line">    component: <span class="built_in">require</span>(<span class="string">'./components/Demo.vue'</span>),</span><br><span class="line">    children: [</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'DemoVuexState'</span>,</span><br><span class="line">        path: <span class="string">'vuex_state'</span>,</span><br><span class="line">        meta: &#123;</span><br><span class="line">          title: <span class="string">'vuex演示'</span></span><br><span class="line">        &#125;,</span><br><span class="line">        component: <span class="built_in">require</span>(<span class="string">'./components/DemoVuexState.vue'</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> routes</span><br></pre></td></tr></table></figure></p>
<p>如此这般，各个页面的<code>title</code>就预设好了</p>
<p>小明：”为什么<code>title</code>里不加上站点名后缀？像<code>demo - leenty blog</code>这样？“<br>老师：“滚出去！”</p>
<p>其实是这样的，后缀如果一个个加也是可以的，但为什么不用语句帮我们加上去呢？<br>这样就一劳永逸啦，再也不用自己一个个打后缀了，哈哈哈，真TM机智！<br><img src="http://www.leenty.com/img/vue/mdzz.jpg" alt="mdzz"></p>
<h4 id="路由导航钩子介绍"><a href="#路由导航钩子介绍" class="headerlink" title="路由导航钩子介绍"></a>路由导航钩子介绍</h4><p>讲一讲这个所谓的全局导航钩子，听起来玄不愣登的。。。</p>
<p>导航是发生在路由改变时的事件，这也是为何网页的导航条叫导航条的原因<br>尤大大的原话是：“正如其名，vue-router 提供的导航钩子主要用来拦截导航，让它完成跳转或取消。有多种方式可以在路由导航发生时执行钩子：全局的, 单个路由独享的, 或者组件级的”<br>说的很明白，言简意赅，其实就是能让你控制导航的一个方法而已<br>导航钩子分为全局，单个路由独享和组件级别的。<br>但不论如何，导航钩子都接受一个函数为参数，并会在导航过程中调用这个函数。<br>函数会被传入3个参数，分别为<code>to, from, next</code><br>没错，你看字面意思应该理解了个大概，即：<br><code>from</code>：你从哪里来？(问询消息的小弟A)<br><code>to</code>：要到哪里去？(问询消息的小弟B)<br><code>next</code>：让不让过去还得看老子我的！(大哥你懂不)</p>
<p>上面这位大哥(<code>next</code>)会有三中方法！<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">next() <span class="comment">// 默认通过路由</span></span><br><span class="line">next(<span class="literal">false</span>) <span class="comment">// 中止导航，那么将会跳回到from的地址</span></span><br><span class="line">next(&#123; <span class="attr">path</span>: <span class="string">'/'</span> &#125;) <span class="comment">// 跟一个路由参数对象，将会中止当前导航并跳往指向的路由</span></span><br></pre></td></tr></table></figure></p>
<p>好的，先看看全局的写法<br><strong>全局导航钩子</strong>一共两个，<code>router.beforeEach</code>和<code>router.afterEach</code><br>一个触发于导航开始前，一个触发于导航开始后。用法呢，都是一样的，如下！<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123; ... &#125;)</span><br><span class="line"></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">  next(<span class="literal">false</span>) <span class="comment">// 大哥：谁让你过去的？</span></span><br><span class="line">  <span class="comment">// 调用next(false)中止导航，于是页面回到跳转前</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">router.afterEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">  next() <span class="comment">// 大哥：过去吧！</span></span><br><span class="line">  <span class="comment">// 调用next通过路由</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="string">``</span></span><br><span class="line"></span><br><span class="line">**单个路由独享的钩子**，同样是两个方法<span class="string">`beforeEnter`</span>和<span class="string">`afterEnter`</span>，同样的套路。</span><br><span class="line">套路如下：</span><br><span class="line"><span class="string">``</span><span class="string">`js</span></span><br><span class="line"><span class="string">const router = new VueRouter(&#123;</span></span><br><span class="line"><span class="string">  routes: [</span></span><br><span class="line"><span class="string">    &#123;</span></span><br><span class="line"><span class="string">      path: '/demo',</span></span><br><span class="line"><span class="string">      component: Demo,</span></span><br><span class="line"><span class="string">      beforeEnter: (to, from, next) =&gt; &#123;</span></span><br><span class="line"><span class="string">        console.log('小弟B：哎呀妈呀！大兄弟，这是要去哪呀？', to)</span></span><br><span class="line"><span class="string">        console.log('小弟A：大兄弟，哪儿旮沓的呀！', from)</span></span><br><span class="line"><span class="string">        next() // 大哥：过去吧！</span></span><br><span class="line"><span class="string">        // 调用next通过路由</span></span><br><span class="line"><span class="string">      &#125;,</span></span><br><span class="line"><span class="string">      afterEnter: (to, from, next) =&gt; &#123;</span></span><br><span class="line"><span class="string">        console.log('小弟B：哎呀妈呀！大兄弟，这是要去哪呀？', to)</span></span><br><span class="line"><span class="string">        console.log('小弟A：大兄弟，哪儿旮沓的呀！', from)</span></span><br><span class="line"><span class="string">        next(&#123; path: '/' &#125;) // 大哥：像那边走！</span></span><br><span class="line"><span class="string">        // 调用next(&#123; path: '/' &#125;)中止导航，并跳到首页</span></span><br><span class="line"><span class="string">      &#125;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">  ]</span></span><br><span class="line"><span class="string">&#125;)</span></span><br></pre></td></tr></table></figure></p>
<p><strong>组件内的钩子</strong>，依然是一对基友方法<code>beforeRouteEnter</code>和<code>beforeRouteLeave</code><br>套路还是一样的0.0<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Demo = &#123;</span><br><span class="line">  template: <span class="string">`&lt;div&gt;this is a Demo &lt;/div&gt;`</span>,</span><br><span class="line">  beforeRouteEnter (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">    next() <span class="comment">// 大哥：过去吧！</span></span><br><span class="line">    <span class="comment">// 在渲染该组件的对应路由被 confirm 前调用</span></span><br><span class="line">    <span class="comment">// 不！能！获取组件实例 `this`</span></span><br><span class="line">    <span class="comment">// 因为当钩子执行前，组件实例还没被创建</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeRouteLeave (to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟B：哎呀妈呀！大兄弟，这是要去哪呀？'</span>, to)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'小弟A：大兄弟，哪儿旮沓的呀！'</span>, <span class="keyword">from</span>)</span><br><span class="line">    next() <span class="comment">// 大哥：过去吧！</span></span><br><span class="line">    <span class="comment">// 导航离开该组件的对应路由时调用</span></span><br><span class="line">    <span class="comment">// 可以访问组件实例 `this`</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="配合路由全局导航钩子去更新title"><a href="#配合路由全局导航钩子去更新title" class="headerlink" title="配合路由全局导航钩子去更新title"></a>配合路由全局导航钩子去更新<code>title</code></h4><p>好的，三种都介绍完了，那么打开<code>src/router.js</code>，没错，这回是<code>router.js</code>，这是咱装载路由的文件</p>
<p>在此之前，我们还需要知道在一个嵌套路由情况下的节点分布。<br>三个参数之一的<code>to</code>存在属性<code>to.matched</code>,里面存在了一个包含路由节点的数组<br>顺序是从子路由到根路由</p>
<p>好的，确定下title文案</p>
<table>
<thead>
<tr>
<th style="text-align:left">router</th>
<th style="text-align:center">title</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><code>├── home</code></td>
<td style="text-align:center">leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>├── article</code></td>
<td style="text-align:center">article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>│   ├── vue2-1</code></td>
<td style="text-align:center">vue2.0一起在懵逼的海洋里越陷越深（一） - article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>│   ├── ...</code></td>
<td style="text-align:center">… - article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>│   └── vue2-6</code></td>
<td style="text-align:center">vue2.0一起在懵逼的海洋里越陷越深（六） - article - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>└── demo</code></td>
<td style="text-align:center">demo - leenty blog</td>
</tr>
<tr>
<td style="text-align:left"><code>└── demo-1</code></td>
<td style="text-align:center">具体演示1 - demo - leenty blog</td>
</tr>
</tbody>
</table>
<p>里面的结构是这样的<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> VueRouter <span class="keyword">from</span> <span class="string">'vue-router'</span></span><br><span class="line"><span class="keyword">import</span> routes <span class="keyword">from</span> <span class="string">'./routes'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> title = <span class="string">'leenty blog'</span></span><br><span class="line"><span class="comment">// 定义我们站点的名字</span></span><br><span class="line"></span><br><span class="line">Vue.use(VueRouter)</span><br><span class="line"></span><br><span class="line"><span class="comment">/* eslint-disable no-new */</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  mode: <span class="string">'history'</span>,</span><br><span class="line">  linkActiveClass: <span class="string">'u-link--Active'</span>,</span><br><span class="line">  routes</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 路由导航钩子，beforeEach，在路由进入前调用</span></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> titleStr = <span class="string">''</span></span><br><span class="line">  <span class="comment">// 检测是不是要跳转首页，如果是，则不处理</span></span><br><span class="line">  <span class="keyword">if</span> (to.name !== <span class="string">'Home'</span>) &#123;</span><br><span class="line">    <span class="comment">// 倒序遍历数组获取匹配到的路由节点，拼接各部分title</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = to.matched.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">      titleStr += <span class="string">`<span class="subst">$&#123;to.matched[i].meta.title&#125;</span> - `</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 添加站点名</span></span><br><span class="line">  titleStr += title</span><br><span class="line">  <span class="comment">// 更新title</span></span><br><span class="line">  <span class="built_in">document</span>.title = titleStr</span><br><span class="line">  <span class="comment">// 继续路由导航</span></span><br><span class="line">  next()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> router</span><br></pre></td></tr></table></figure></p>
<p>ok，打完收工！现在可以切换路由看看<code>title</code>有没有在变化了。<br>可以看我的Demo<a href="http://vue2.leenty.com" target="_blank" rel="noopener">http://vue2.leenty.com</a>，四处切换路由，看看标题如何变化吧！</p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><p><a href="http://vue2.leenty.com" target="_blank" rel="noopener">演示地址(http://vue2.leenty.com)</a><br><a href="https://github.com/leenty/vue2" target="_blank" rel="noopener">源码地址(https://github.com/leenty/vue2)</a><br><a href="https://github.com/leenty" target="_blank" rel="noopener">github主页</a>,觉得靠谱的话欢迎加星跟随</p>

      
    </div>
    <div class="article-info article-info-index">
      
      <a href="/2016/12/18/vue2-6/" class="archive-article-date">
  	<time datetime="2016-12-18T14:47:23.000Z" itemprop="datePublished"><i class="icon-clock"></i>2016-12-18</time>
</a>
      
	<div class="article-tag tagcloud">
		<i class="icon-price-tags"></i>
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue-router/">vue-router</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vuejs/">vuejs</a></li></ul>
	</div>

      

      <div class="clearfix"></div>
    </div>
  </div>
</article>

  
<nav id="article-nav">
  
  
    <a href="/2016/12/11/vue2-5/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">vue2.0一起在懵逼的海洋里越陷越深（五）</div>
      <i class="icon-circle-right"></i>
    </a>
  
</nav>




<div class="share_jia">
	<!-- JiaThis Button BEGIN -->
	<div class="jiathis_style">
		<span class="jiathis_txt">Share to: &nbsp; </span>
		<a class="jiathis_button_facebook"></a> 
	    <a class="jiathis_button_twitter"></a>
	    <a class="jiathis_button_plus"></a> 
	    <a class="jiathis_button_tsina"></a>
		<a class="jiathis_button_cqq"></a>
		<a class="jiathis_button_douban"></a>
		<a class="jiathis_button_weixin"></a>
		<a class="jiathis_button_tumblr"></a>
    <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	</div>
	<script type="text/javascript" src="//v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
	<!-- JiaThis Button END -->
</div>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="vue2-6" data-title="vue2.0一起在懵逼的海洋里越陷越深（六）" data-url="http://baidu.com/2016/12/18/vue2-6/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"leenty-blog"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>





      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2019 leenty
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    <script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: false,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false,
		root: "/",
		innerArchive: true
	}
</script>

<script src="/./main.js"></script>


    
<div class="tools-col">
  <ul class="btn-wrap">
    
      <li class="chose" data-hook="tools-section-all"><span class="text">全部</span><i class="icon-book"></i></li>
    
    
      <li data-hook="tools-section-tag"><span class="text">标签</span><i class="icon-price-tags"></i></li>
    
    
      <li data-hook="tools-section-friends"><span class="text">友链</span><i class="icon-link"></i></li>
    
    
      <li data-hook="tools-section-me"><span class="text">我</span><i class="icon-smile"></i></li>
    
  </ul>
  <div class="tools-wrap">
    
    	<section class="tools-section tools-section-all chose">
    	</section>
    

    
    	<section class="tools-section tools-section-tag">
    			<div class="widget tagcloud" id="js-tagcloud">
    				<a href="/tags/ES6/" style="font-size: 10px;">ES6</a> <a href="/tags/css/" style="font-size: 15px;">css</a> <a href="/tags/git/" style="font-size: 10px;">git</a> <a href="/tags/github/" style="font-size: 10px;">github</a> <a href="/tags/gulp/" style="font-size: 10px;">gulp</a> <a href="/tags/hexo/" style="font-size: 12.5px;">hexo</a> <a href="/tags/js/" style="font-size: 12.5px;">js</a> <a href="/tags/other/" style="font-size: 10px;">other</a> <a href="/tags/sublime/" style="font-size: 10px;">sublime</a> <a href="/tags/vim/" style="font-size: 10px;">vim</a> <a href="/tags/vue-router/" style="font-size: 17.5px;">vue-router</a> <a href="/tags/vuejs/" style="font-size: 20px;">vuejs</a> <a href="/tags/vuex/" style="font-size: 12.5px;">vuex</a>
    			</div>
    	</section>
    

    
    	<section class="tools-section tools-section-friends">
  		
  			<div class="friends-wrap" id="js-friends">
  			
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="http://vue2.leenty.com">vue2.0演示地址</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.leenty.com/">leenty的博客</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="https://whqet.github.io/">whqet的博客</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="https://shenyubin.github.io/">沈雨彬的博客</a>
  	        
  	          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.deboy.cn">Deboy的博客</a>
  	        
  	        </div>
  		
    	</section>
    

    
    	<section class="tools-section tools-section-me">
  	  	
  	  		<div class="aboutme-wrap" id="js-aboutme">不会捣(xia)鼓(gao)的前端不是好全栈</div>
  	  	
    	</section>
    
  </div>
  
</div>
    <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>
  </div>
</body>
</html>